package com.ckzp.jfinal.plugins;

import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import com.ckzp.core.ConfigUtil;
import com.ckzp.core.Results;
import com.ckzp.core.file.FileControl;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.util.DateUtil;
import com.ckzp.core.util.ImageUtil;
import com.ckzp.core.util.JwtUtil;
import com.ckzp.core.validate.FileValidate;
import com.ckzp.jfinal.system.WebSite;
import com.ckzp.jfinal.system.model.SysFile;
import com.jfinal.log.Log;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;

/**
 * Created by 51594 on 2023/8/25.
 */
public class UpDocument {


    public static final Log log = Log.getLog(UpImage.class);

    public static String UPLOAD_EXT = "|pdf|jpg|png|gif|zip|rar|dmp|mp4|doc|docx|xls|xlsx|ppt|pptx|";

    public static boolean DEBUG = ConfigUtil.DEBUG();

    public static UpDocument n() {
        return new UpDocument();
    }

    public static final String IMAGE_SAVE_PATH = ConfigUtil.getProperty("FILE_SAVE_PATH");

    public static final String FILE_VIEW_PATH = "https://tpfub.tyfo.com:4434/tyfoSrvEx/downFile";

    public static final String IMAGE_VIEW_OUT_PATH = ConfigUtil.getProperty("FILE_VIEW_OUT_PATH");

    public String file_name;

    public String file_ext;

    public String save_name;

    public String save_path;

    public long file_size = 0;

    public String view_path;
    //反回表单中其它值
    public Map req = new HashMap();


    public String getFile_name() {
        return file_name;
    }

    public UpDocument setFile_name(String file_name) {
        this.file_name = file_name;
        return this;
    }

    public String getFile_ext() {
        return file_ext;
    }

    public long getFile_size() {
        return file_size;
    }

    public void setFile_size(long file_size) {
        this.file_size = file_size;
    }

    public void setFile_ext(String file_ext) {
        this.file_ext = file_ext;
    }

    public String getSave_name() {
        return save_name;
    }

    public UpDocument setSave_name(String save_name) {
        this.save_name = save_name;
        return this;
    }

    public String getSave_path() {
        return save_path;
    }

    public UpDocument setSave_path(String save_path) {
        this.save_path = save_path;
        return this;
    }

    public String getView_path() {
        return view_path;
    }

    public UpDocument setView_path(String view_path) {
        this.view_path = view_path;
        return this;
    }


    /**
     * l
     *
     * @param request
     * @param basepath
     * @param needyyyymm
     * @return
     */
    public Results upload(HttpServletRequest request, String basepath, boolean needyyyymm) {
        return upload(request, basepath, needyyyymm, true);
    }

    /**
     * l
     *
     * @param request
     * @param basepath
     * @return
     */
    public Results upload(HttpServletRequest request, String basepath) {
        return upload(request, basepath, true, true);
    }


    /**
     * l
     *
     * @param request
     * @param basepath
     * @param rename
     * @param needyyyymm
     * @return
     */
    public Results upload(HttpServletRequest request, String basepath, boolean needyyyymm, boolean rename) {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        Results results = Results.n(0);

        if (isMultipart) {
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = upload.parseRequest(request);
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String content = item.getString("UTF-8");
                        req.put(fieldName, content);
                    } else {
                        file_name = item.getName();
                        String ext = getExt(file_name);
                        setFile_ext(ext);
                        if (!validateExt(ext)) {
                            results.setCode(9).setMsg("不允许上传[" + ext + "]文件").setMessage("不允许上传[" + ext + "]文件");
                        } else if (file_name != null && file_name != "") {
                            String yyyymm = DateUtil.getDateYYYYMM();
                            String comm_path = "/" + basepath + "/";
                            if (needyyyymm) comm_path += yyyymm + "/";
                            if (rename) {
                                save_name = ImageUtil.getFileRename(file_name);
                            } else {
                                save_name = file_name;
                            }
                            comm_path += save_name;
                            save_path = comm_path;
                            view_path = TransUrl(request, comm_path);
                            String paths = IMAGE_SAVE_PATH + comm_path;
                            paths = FileValidate.validatePath(paths);
                            FileControl.n(paths).createDirectory();
                            if (DEBUG) System.out.println("保存路经：" + paths);
                            File save = new File(paths);
                            item.write(save);
                            file_size = save.length();
                            //////////////////////////////////////
                            new SysFile().set("file_path", save_path)
                                    .set("file_name", file_name)
                                    .set("file_size", save.length())
                                    .set("create_time", new Date())
                                    .set("save_month", yyyymm)
                                    .set("file_ext", ext)
                                    .set("update_user", getEmpID(request))
                                    .set("file_type", getFileType(ext))
                                    .save();
                            /////////////////////////////////
                            results.setMsg("上传成功");
                            results.setObject(this);
                        }
                    }
                }
            } catch (FileUploadException e) {
                results.setCode(9);
                results.setMsg("上传失败1");
                results.setMessage(e.getMessage());
            } catch (Exception e) {
                results.setCode(9);
                results.setMsg("上传失败2");
                results.setMessage(e.getMessage());
            }
        }
//        System.out.println(results.toJson());
        return results;
    }

    /**
     * @param request
     * @param basepath
     * @param needyyyymm
     * @param rename
     * @return
     */
    public Jmode uploadEdit(HttpServletRequest request, String basepath, boolean needyyyymm, boolean rename) {
        return uploadEdit(request, basepath, needyyyymm, rename, 0);
    }

    /**
     * l
     *
     * @param request
     * @param basepath
     * @param rename
     * @param needyyyymm
     * @param width      宽度，0表示不压缩
     * @return
     */
    public Jmode uploadEdit(HttpServletRequest request, String basepath, boolean needyyyymm, boolean rename, int width) {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        Jmode jmode = Jmode.n();
        int errno = 0;
        List data = new ArrayList();
        if (isMultipart) {
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = upload.parseRequest(request);

                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String content = item.getString("UTF-8");
                        req.put(fieldName, content);
                    } else {
                        file_name = item.getName();
                        String ext = getExt(file_name);
                        if (!validateExt(ext)) {
                            errno = 9;
                        } else if (file_name != null && file_name != "") {
                            String yyyymm = DateUtil.getDateYYYYMM();
                            String comm_path = "/" + basepath + "/";
                            if (needyyyymm) comm_path += yyyymm + "/";
                            FileUtil.mkdir(IMAGE_SAVE_PATH + comm_path);
                            if (rename) {
                                save_name = ImageUtil.getFileRename(file_name);
                            } else {
                                save_name = file_name;
                            }
                            comm_path += save_name;
                            save_path = comm_path;
                            view_path = FILE_VIEW_PATH + comm_path;
                            String paths = IMAGE_SAVE_PATH + comm_path;
                            paths = FileValidate.validatePath(paths);
                            if (DEBUG) System.out.println("保存路经：" + paths);
                            File save = new File(paths);
                            item.write(save);
                            //重置大小/////////////////////
                            //////////////////////////////////////
                            new SysFile().set("file_path", save_path)
                                    .set("file_name", file_name)
                                    .set("file_size", save.length())
                                    .set("create_time", new Date())
                                    .set("save_month", yyyymm)
                                    .set("file_ext", ext)
                                    .set("update_user", getEmpID(request))
                                    .set("file_type", getFileType(ext))
                                    .save();
                            /////////////////////////////////
                            data.add(Jmode.n().set("url", view_path).set("alt", "").set("href", ""));
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.getMessage());
                errno = 9;
            }
        }
        jmode.set("errno", errno).set("data", data);
        return jmode;
    }

    /**
     * l
     *
     * @param urls
     * @param basepath
     * @param rename
     * @param needyyyymm
     * @return
     */
    public Results upload(String urls, String basepath, boolean needyyyymm, boolean rename) {
        Results results = Results.n(0);
        try {
            if (urls != null && urls != "") {
                String yyyymm = DateUtil.getDateYYYYMM();
                String comm_path = "/" + basepath + "/";
                if (needyyyymm) comm_path += yyyymm + "/";
                save_name = ImageUtil.getFileRename(urls);
                comm_path += save_name;
                save_path = comm_path;
                view_path = FILE_VIEW_PATH + comm_path;
                String paths = IMAGE_SAVE_PATH + comm_path;
                FileControl.n(paths).createDirectory();
                // if (DEBUG) System.out.println("保存路经：" + paths);
                System.out.println("保存路经：" + paths);
                MyX509TrustManager.downLoadFromUrlHttps(urls, paths);
                results.setMsg("上传成功");
                results.setObject(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
            results.setCode(9);
            results.setMsg("上传失败");
            results.setMessage(e.getMessage());
        }
        return results;
    }


    /**
     * l
     *
     * @param basepath
     * @param basepath
     * @param needyyyymm
     * @return
     */
    public Results upload(String urls, String basepath, boolean needyyyymm, String ext) {
        Results results = Results.n(0);
        try {
            if (urls != null && urls != "") {
                String yyyymm = DateUtil.getDateYYYYMM();
                String comm_path = "/" + basepath + "/";
                if (needyyyymm) comm_path += yyyymm + "/";
                save_name = DateUtil.getDate().getTime() + "." + ext;
                comm_path += save_name;
                save_path = comm_path;
                view_path = FILE_VIEW_PATH + comm_path;
                String paths = IMAGE_SAVE_PATH + comm_path;
                FileControl.n(paths).createDirectory();
                // if (DEBUG) System.out.println("保存路经：" + paths);
                System.out.println("保存路经：" + paths);
                MyX509TrustManager.downLoadFromUrlHttps(urls, paths);
                results.setMsg("上传成功");
                results.setObject(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
            results.setCode(9);
            results.setMsg("上传失败");
            results.setMessage(e.getMessage());
        }
        return results;
    }


    public static String TransUrl(String url) {
        if (url == null) return "";
        if (url.length() == 0) return "";
        if (url.indexOf("http") > -1) return url;
        return FILE_VIEW_PATH + url;
    }


    public static String TransDocumentUrl(String url) {
        if (url == null) return "";
        if (url.length() == 0) return "";
        if (url.indexOf("http") > -1) return url;
        return FILE_VIEW_PATH + url;
    }


    public static String TransDocumentUrl(String filename, String url) {
        if (url == null) return "";
        if (url.length() == 0) return "";
        if (url.indexOf("http") > -1) return url;
        StringBuffer sb = new StringBuffer(FILE_VIEW_PATH);
        sb.append("?fileName=" + filename);
        sb.append("&tfsName=" + url);
        return sb.toString();
    }

    /**
     * 动态输出访问地址
     *
     * @param request
     * @param url
     * @return
     */
    public static String TransUrl(HttpServletRequest request, String url) {
        if (url == null) return "";
        if (url.length() == 0) return "";
        if (url.indexOf("http") > -1) return url;
        String host = request.getHeader("Host");
        if (host == null) host = "";
        String TAGS = ConfigUtil.getProperty("IMAGE_VIEW_PATH2_TAG", "");
        String IMAGE_VIEW_PATH = ConfigUtil.getProperty("IMAGE_VIEW_PATH", "");
        String IMAGE_VIEW_PATH2 = ConfigUtil.getProperty("IMAGE_VIEW_PATH2", "");
        if (TAGS.length() > 0) {
            if (host.indexOf(TAGS) > -1) {
                return IMAGE_VIEW_PATH2 + url;
            } else {
                return IMAGE_VIEW_PATH + url;
            }
        } else {
            return IMAGE_VIEW_PATH + url;
        }
    }


    public static String OutTransUrl(String url) {
        if (url == null) return "";
        if (url.length() == 0) return "";
        if (url.indexOf("http") > -1) return url;
        return IMAGE_VIEW_OUT_PATH + url;
    }


    public static String ViewPath(String url) {
        if (url == null) return "";
        if (url.length() == 0) return "";
        return FILE_VIEW_PATH + url;
    }


    public static String SavePath(String url) {
        if (url == null) return "";
        if (url.length() == 0) return "";
        return IMAGE_SAVE_PATH + url;
    }


    /**
     * 验证是否可以上传
     *
     * @param file_ext
     * @return
     */
    protected boolean validateExt(String file_ext) {
        if (UPLOAD_EXT.indexOf("|" + file_ext + "|") > -1) {
            return true;
        }
        return false;
    }

    /**
     * 取得扩展名
     *
     * @param file_name
     * @return
     */
    protected String getExt(String file_name) {
        if (file_name == null) return "";
        int index = file_name.lastIndexOf(".");
        String ext = "";
        if (index > 0 && (file_name.length() >= index + 1)) {
            ext = file_name.substring(index + 1, file_name.length());
        }
        if (ext != null) ext = ext.toLowerCase();
        return ext;
    }

    /**
     * @return
     */
    protected int getEmpID(HttpServletRequest request) {
        String jwt = WebSite.getJwt(request);
        Results results = JwtUtil.validateJWT(jwt);
        if (results.getCode() == 0) {
            JwtUtil.JwtSubject js = results.getObject(JwtUtil.JwtSubject.class);
            return js.getUserid();
        }
        return 0;
    }


    protected int getFileType(String ext) {
        if (ext == null) return 3;
        ext = ext.toLowerCase();
        if ("|jpg|png|gif|jpeg||||".indexOf("|" + ext + "|") > -1) {
            return 1;//图片
        } else if ("|mp4|mp3|||||".indexOf("|" + ext + "|") > -1) {
            return 2;//图片
        } else {
            return 3;
        }
    }

    public static String getFileSize(long filesize) {
        if (filesize > 1024 * 1024 * 1024) {
            return String.valueOf((filesize / (1024 * 1024 * 1024))) + " GB";
        } else if (filesize > 1024 * 1024) {
            return String.valueOf((filesize / (1024 * 1024))) + " MB";
        } else if (filesize > 1024) {
            return String.valueOf((filesize / (1024))) + " KB";
        } else {
            return String.valueOf((filesize / (1024))) + " KB";
        }
    }


    public static void main(String[] arg) {
        try {
            String urls = "https://tpfub.tyfo.com:4434/tyfoSrvEx/imagedeal?path=T19ZYbBbCT1R4bAZ6K.jpg";
            MyX509TrustManager.downLoadFromUrlHttps(urls, "d:/1.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
